#include "EntityProjectile.h"
#include "ComponentManager.h"
#include <SDL.h>

CEntityProjectile::CEntityProjectile(int indexTexture, int indexSprite, const CVector2i& position, bool collide, int speed)
	:CWorldEntity(indexTexture, position, collide), 
	m_speed(speed), m_indexSprite(indexSprite), m_birthTime(-1)
{
	m_active = false;
}

CEntityProjectile::~CEntityProjectile(){}

void CEntityProjectile::doUpdate(void)
{
#ifdef _DEBUG
	CM.PROFILER().startCount("EntityProjectile Update");
#endif

	if(m_healthPoint<=0)
	{
		m_active=false;
		CM.EXPLOSION().activeExplosion(eProjectileExplosion, m_position);
	}

	if(m_birthTime == -1)
		m_birthTime = SDL_GetTicks();

	int currentTime = SDL_GetTicks();
	if(m_birthTime + m_liveTime < currentTime)
	{
		m_birthTime=-1;
		m_active = false;
	}

	m_previousPosition = m_position;
	m_position.m_x+=m_speed;

	//check collision
	CWorldEntity* collidedWith = CM.WORLD().checkCollision(this);
	if(collidedWith!=0)
	{
		if(collidedWith->getSide()!=m_side)
		{
			collidedWith->setHealthPoint(collidedWith->getHealthPoint()-m_damagePoint);
		}
		CM.EXPLOSION().activeExplosion(eProjectileExplosion, m_position);
		m_active=false;
		m_position = m_previousPosition;
	}

#ifdef _DEBUG
	CM.PROFILER().endCount("EntityProjectile Update");
#endif
}

void CEntityProjectile::doRender(void)
{
	if(!m_active)
		return;

	CM.VISU().displaySprite(m_indexGfx, m_indexSprite, m_position);
}

void CEntityProjectile::setSpeed(int speed)
{
	m_speed = speed;
}

void CEntityProjectile::setIndexSprite(int index)
{
	m_indexSprite = index;
}

void CEntityProjectile::setIndexTexture(int index)
{
	m_indexGfx = index;
}

int CEntityProjectile::getSpeed(void)
{
	return m_speed;
}
